package io.renren.modules.eas.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.utils.Query;
import io.renren.modules.eas.entity.EasEduthemeAspectEntity;
import io.renren.modules.eas.service.EasEduthemeAspectService;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.eas.entity.EasCommentKeysEntity;
import io.renren.modules.eas.service.EasCommentKeysService;



/**
 * 关键词表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2023-09-26 23:32:06
 */
@RestController
@RequestMapping("eas/eascommentkeys")
public class EasCommentKeysController {
    @Autowired
    private EasCommentKeysService easCommentKeysService;

    @Autowired
    private EasEduthemeAspectService easEduthemeAspectService;

    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("eas:eascommentkeys:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = easCommentKeysService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("eas:eascommentkeys:info")
    public R info(@PathVariable("id") Long id){
		EasCommentKeysEntity easCommentKeys = easCommentKeysService.getById(id);

        return R.ok().put("easCommentKeys", easCommentKeys);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("eas:eascommentkeys:save")
    public R save(@RequestBody EasCommentKeysEntity easCommentKeys){
		easCommentKeysService.save(easCommentKeys);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("eas:eascommentkeys:update")
    public R update(@RequestBody EasCommentKeysEntity easCommentKeys){
		easCommentKeysService.updateById(easCommentKeys);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("eas:eascommentkeys:delete")
    public R delete(@RequestBody Long[] ids){
		easCommentKeysService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 根据条件查询 关键词
     * @return
     */
    @RequestMapping("/keys")
    public R keys(){

        List<Map> maps = easCommentKeysService.selectGroupKeys();
        HashMap<Object, Object> hashMap = new HashMap<>();
        Map<Object, Object> collect = maps.stream().collect(Collectors.toMap(map -> map.get("educationName"), map -> map.get("factor")));
        for (Map.Entry<Object, Object> entry : collect.entrySet()) {
            Map<Object, Object> eduaspectName = ((List<Map>)(entry.getValue())).stream().collect(Collectors.toMap(map -> map.get("factor"),
                    map ->  ((List)map.get("aspect")).stream().collect(
                            Collectors.toMap(aspect->((Map)aspect).get("aspect"),
                                    aspect->( (List)((Map)aspect).get("keys")).stream().collect(Collectors.groupingBy(key->((Map)key).get("keysLevel"))
                            )))));
            hashMap.put(entry.getKey(),eduaspectName);
        }
        return R.ok().put("keys", hashMap);
    }


    @RequestMapping("/keysByCreate")
    public R keysByCreate(){
        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        List<Map> maps  =  easCommentKeysService.keysByCreate(sysUserEntity.getUserId());
        HashMap<Object, Object> hashMap = new HashMap<>();
        Map<Object, Object> collect = maps.stream().collect(Collectors.toMap(map -> map.get("educationName"), map -> map.get("factor")));
        for (Map.Entry<Object, Object> entry : collect.entrySet()) {
            Map<Object, Object> eduaspectName = ((List<Map>)(entry.getValue())).stream().collect(Collectors.toMap(map -> map.get("factor"),
                    map ->  ((List)map.get("aspect")).stream().collect(
                            Collectors.toMap(aspect->((Map)aspect).get("aspect"),
                                    aspect->( (List)((Map)aspect).get("keys")).stream().collect(Collectors.groupingBy(key->((Map)key).get("keysLevel"))
                                    )))));
            hashMap.put(entry.getKey(),eduaspectName);
        }
        return R.ok().put("keys", hashMap);
    }


    /**
     * 添加新自定义关键词
     * @param easCommentKeys
     * @return
     */
    @RequestMapping("/addNewKey")
    public R addNewKey(@RequestBody EasCommentKeysEntity easCommentKeys){
        EasCommentKeysEntity one = easCommentKeysService.lambdaQuery().eq(EasCommentKeysEntity::getKeys, easCommentKeys.getKeys()).one();
        if (one!=null){
            return R.error("关键词已存在");
        }
        EasEduthemeAspectEntity easEduthemeAspectEntity = easEduthemeAspectService.lambdaQuery()
                .eq(EasEduthemeAspectEntity::getAspect, easCommentKeys.getAspectStr())
                .one();
        easCommentKeys.setEducationId(easEduthemeAspectEntity.getEducationId());
        easCommentKeys.setEduthemeId(easEduthemeAspectEntity.getEduthemeId());
        easCommentKeys.setEduaspectId(easEduthemeAspectEntity.getId());
        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        easCommentKeys.setCreateBy(sysUserEntity.getUserId());
        easCommentKeysService.save(easCommentKeys);
        return R.ok();
    }

    /**
     * 获取自定义关键词
     * @param params
     * @return
     */
    @RequestMapping("/getCustomKeys")
    public R getCustomKeys(@RequestParam Map<String, Object> params){
        IPage<EasCommentKeysEntity> page = easCommentKeysService.lambdaQuery()
                .eq(EasCommentKeysEntity::getType, 1)
                .page(new Query<EasCommentKeysEntity>().getPage(params));

        PageUtils utils = new PageUtils(page);
        return R.ok().put("page", utils);
    }

    /**
     * 修改自定义关键词状态
     * @return
     */
    @RequestMapping("/updateStatusCustomKeys")
    public R updateStatusCustomKeys(Integer id,Integer status){
        easCommentKeysService.lambdaUpdate()
                .set(EasCommentKeysEntity::getStatus, status)
                .eq(EasCommentKeysEntity::getId, id)
                .update();
        return R.ok();
    }

    @RequestMapping("/updateByAspect")
    public R updateByAspect(Integer id,String aspect,String keysLevel){
        EasEduthemeAspectEntity one = easEduthemeAspectService.lambdaQuery().eq(EasEduthemeAspectEntity::getAspect, aspect)
                .one();
        EasCommentKeysEntity entity = easCommentKeysService.getById(id);
        entity.setEducationId(one.getEducationId());
        entity.setEduthemeId(one.getEduthemeId());
        entity.setEduaspectId(one.getId());
        entity.setKeysLevel(keysLevel);
        easCommentKeysService.updateById(entity);
        return R.ok();
    }

}
